import datetime
import os
import random
import sqlite3
import time

import matplotlib
import numpy as np
import pandas as pd
import xlwt
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QUrl, QDate
from PyQt5.QtGui import QDesktopServices, QFont
from PyQt5.QtWidgets import QMainWindow, QToolBar, QAbstractItemView, QHeaderView

from common.BaseSettings import read_user_dict
from common.settings import *
from ui.base.windows.BaseWindow import BaseWindow

matplotlib.rcParams['backend'] = 'Qt5Agg'

try:
    from common.utils.NovishLogger import logger
except:
    from loguru import logger


class UiBaseDateReview(QMainWindow, BaseWindow):
    def __init__(self, db: str = ''):
        QMainWindow.__init__(self)
        BaseWindow.__init__(self)

        self.page_cnt = 1  # 总页数
        self.db_path = db  # 数据库路径
        self.table_name = 'RESULT_DATA'  # 表名
        self.table_header = []  # 表头
        self.table_limit = 100  # 每页数据条目总数
        self.result = None  # 数据库查询结果
        self.t_begin = time.mktime((datetime.datetime(2022, 1, 1, 0, 0).timetuple()))
        self.t_end = time.mktime(datetime.datetime.now().timetuple())
        self.sql = f'select * from {self.table_name}'
        self.sql2 = ''
        self.threshold = []
        self._initUI()
        # self._connect()
        self.table_left_class = [
            '总数', 'MAX', 'MIN', 'AVE',
            # 'σL',
            # 'σ',
            # '-6σ',
            # '-4σ',
            # '-3σ',
            # '+3σ',
            # '+4σ',
            # '+6σ',
            # 'UL',
            # 'LL',
            # 'AMAX',
            # 'AMIN',
            # # 'Standard values',
            # 'CP',
            # 'CPK',
            # 'UL (UP Limit)',
            # 'LL (LOW Limit)',
            # '阈值范围',
        ]
        self.head = [[classname] for classname in Settings.DEFECT_MAP.keys()]
        self.class_cnt = len(self.head)
        self.table_header = [classname_ch for classname_ch in Settings.DEFECT_MAP.values()]
        self.data_list = [[] for i in range(self.class_cnt)]
        self.data_size_list = [[] for i in range(self.class_cnt)]
        self.data_area_list = [[] for i in range(self.class_cnt)]
        self.count_list = [0] * self.class_cnt
        self.Max_list = [0] * self.class_cnt
        self.Min_list = [0] * self.class_cnt
        self.Ave_list = [0] * self.class_cnt
        self.SigmaL_list = [[] for i in range(self.class_cnt)]
        self.Sigma_list = [[] for i in range(self.class_cnt)]
        self.Sigma6_list = [[] for i in range(self.class_cnt)]
        self.Sigma4_list = [[] for i in range(self.class_cnt)]
        self.Sigma3_list = [[] for i in range(self.class_cnt)]
        self.Sigma3a_list = [[] for i in range(self.class_cnt)]
        self.Sigma4a_list = [[] for i in range(self.class_cnt)]
        self.Sigma6a_list = [[] for i in range(self.class_cnt)]
        # self.UL_list =[[]for i in range(self.class_cnt)] #Sigma6a_list
        # self.LL_list =[[]for i in range(self.class_cnt)] #Sigma6_list
        self.AMax_list = [[] for i in range(self.class_cnt)]
        self.AMin_list = [[] for i in range(self.class_cnt)]
        self.CP_list = [[] for i in range(self.class_cnt)]
        self.CPK_list = [[] for i in range(self.class_cnt)]
        self.UL_list = [[] for i in range(self.class_cnt)]

        # 显示中文
        # plt.rcParams['font.family'] = 'Microsoft YaHei'
        # plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
        # 显示字符
        # plt.rcParams['axes.unicode_minus'] = False
        self.setWindowTitle('数据追溯')
        self.resize(1700, 900)

    def update_threshold(self):
        USER_DICT = Settings.USER_DICT
        self.threshold = [
            USER_DICT.get('UI_KEY_THRES_ZAZHI', 0.0),
            USER_DICT.get('UI_KEY_BBOX_ZAZHI_W', 0.0),
            USER_DICT.get('UI_KEY_BBOX_ZAZHI_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_HUASHANG', 0.0),
            USER_DICT.get('UI_KEY_BBOX_HUASHANG_W', 0.0),
            USER_DICT.get('UI_KEY_BBOX_HUASHANG_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_HUASHANG-LIGHT', 0.0),
            USER_DICT.get('UI_KEY_BBOX_HUASHANG-LIGHT_W', 0.0),
            USER_DICT.get('UI_KEY_BBOX_HUASHANG-LIGHT_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_PIFENG', 0.0),
            USER_DICT.get('UI_KEY_THRES_PIFENG_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_PIFENG_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_LIANGDIAN', 0.0),
            USER_DICT.get('UI_KEY_THRES_LIANGDIAN_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_LIANGDIAN_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_DIRTY', 0.0),
            USER_DICT.get('UI_KEY_THRES_DIRTY_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_DIRTY_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_BREAK', 0.0),
            USER_DICT.get('UI_KEY_THRES_BREAK_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_BREAK_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_LOUSU', 0.0),
            USER_DICT.get('UI_KEY_THRES_LOUSU_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_LOUSU_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_YAHEN', 0.0),
            USER_DICT.get('UI_KEY_THRES_YAHEN_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_YAHEN_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_YELLOW', 0.0),
            USER_DICT.get('UI_KEY_THRES_YELLOW_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_YELLOW_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_STAIN', 0.0),
            USER_DICT.get('UI_KEY_THRES_STAIN_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_STAIN_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_YIDU', 0.0),
            USER_DICT.get('UI_KEY_THRES_YIDU_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_YIDU_H', 0.0),

        ]

    def reset(self):
        self.data_list = [[] for i in range(self.class_cnt)]
        self.data_size_list = [[] for i in range(self.class_cnt)]
        self.data_area_list = [[] for i in range(self.class_cnt)]
        self.count_list = [0] * self.class_cnt
        self.Max_list = [0] * self.class_cnt
        self.Min_list = [0] * self.class_cnt
        self.Ave_list = [0] * self.class_cnt
        self.SigmaL_list = [[] for i in range(self.class_cnt)]
        self.Sigma_list = [[] for i in range(self.class_cnt)]
        self.Sigma6_list = [[] for i in range(self.class_cnt)]
        self.Sigma4_list = [[] for i in range(self.class_cnt)]
        self.Sigma3_list = [[] for i in range(self.class_cnt)]
        self.Sigma3a_list = [[] for i in range(self.class_cnt)]
        self.Sigma4a_list = [[] for i in range(self.class_cnt)]
        self.Sigma6a_list = [[] for i in range(self.class_cnt)]
        self.AMax_list = [[] for i in range(self.class_cnt)]
        self.AMin_list = [[] for i in range(self.class_cnt)]
        self.CP_list = [[] for i in range(self.class_cnt)]
        self.CPK_list = [[] for i in range(self.class_cnt)]
        self.UL_list = [[] for i in range(self.class_cnt)]

        USER_DICT = Settings.USER_DICT
        self.threshold = [
            USER_DICT.get('UI_KEY_THRES_ZAZHI', 0.0),
            USER_DICT.get('UI_KEY_BBOX_ZAZHI_W', 0.0),
            USER_DICT.get('UI_KEY_BBOX_ZAZHI_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_HUASHANG', 0.0),
            USER_DICT.get('UI_KEY_BBOX_HUASHANG_W', 0.0),
            USER_DICT.get('UI_KEY_BBOX_HUASHANG_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_HUASHANG-LIGHT', 0.0),
            USER_DICT.get('UI_KEY_BBOX_HUASHANG-LIGHT_W', 0.0),
            USER_DICT.get('UI_KEY_BBOX_HUASHANG-LIGHT_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_PIFENG', 0.0),
            USER_DICT.get('UI_KEY_THRES_PIFENG_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_PIFENG_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_LIANGDIAN', 0.0),
            USER_DICT.get('UI_KEY_THRES_LIANGDIAN_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_LIANGDIAN_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_DIRTY', 0.0),
            USER_DICT.get('UI_KEY_THRES_DIRTY_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_DIRTY_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_BREAK', 0.0),
            USER_DICT.get('UI_KEY_THRES_BREAK_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_BREAK_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_LOUSU', 0.0),
            USER_DICT.get('UI_KEY_THRES_LOUSU_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_LOUSU_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_YAHEN', 0.0),
            USER_DICT.get('UI_KEY_THRES_YAHEN_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_YAHEN_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_YELLOW', 0.0),
            USER_DICT.get('UI_KEY_THRES_YELLOW_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_YELLOW_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_STAIN', 0.0),
            USER_DICT.get('UI_KEY_THRES_STAIN_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_STAIN_H', 0.0),

            USER_DICT.get('UI_KEY_THRES_YIDU', 0.0),
            USER_DICT.get('UI_KEY_THRES_YIDU_W', 0.0),
            USER_DICT.get('UI_KEY_THRES_YIDU_H', 0.0),

        ]

    def showEvent(self, event):
        self.SetWindowCentered()
        if os.path.exists(self.db_path):
            self.initData()

    def closeEvent(self, event):
        if os.path.exists(self.db_path):
            self.conn.close()

    def _initUI(self):
        self.central = QtWidgets.QWidget(self)
        self.grid_main = QtWidgets.QGridLayout(self.central)

        self.splitter_paget = QtWidgets.QSplitter(self)
        self.splitter_paget.setHandleWidth(10)
        self.splitter_paget.setChildrenCollapsible(True)

        # 选择时间控件
        self.label1 = QtWidgets.QLabel('开始时间:', self)
        self.label1.setFixedSize(100, 40)
        self.dateEdit1 = QtWidgets.QDateTimeEdit(QDate.currentDate().addDays(-1), self)
        self.dateEdit1.setDisplayFormat('yyyy-MM-dd hh-mm-ss')
        # 设置第一个日期最大值与最小值，在当前日期的基础上，后一年与前一年
        self.dateEdit1.setMinimumDate(QDate.currentDate().addDays(-365))
        self.dateEdit1.setMaximumDate(QDate.currentDate().addDays(365))
        # 设置第一个日历控件允许弹出
        self.dateEdit1.setCalendarPopup(True)

        self.label2 = QtWidgets.QLabel(' 结束时间:', self)
        self.label2.setFixedSize(100, 40)
        # 创建第二个日期时间空间，并把当前日期时间赋值，。并修改显示格式
        self.dateEdit2 = QtWidgets.QDateTimeEdit(QDate.currentDate().addDays(1), self)
        self.dateEdit2.setDisplayFormat('yyyy-MM-dd hh-mm-ss')
        # 设置第二个日期最大值与最小值，在当前日期的基础上，后一年与前一年
        self.dateEdit2.setMinimumDate(QDate.currentDate().addDays(-365))
        self.dateEdit2.setMaximumDate(QDate.currentDate().addDays(365))
        # 设置第二个日历控件允许弹出
        self.dateEdit2.setCalendarPopup(True)

        Time1 = str(self.dateEdit1.dateTime().toPyDateTime())
        Time2 = str(self.dateEdit2.dateTime().toPyDateTime())
        dateTime1 = datetime.datetime.strptime(Time1, "%Y-%m-%d %H:%M:%S")
        dateTime2 = datetime.datetime.strptime(Time2, "%Y-%m-%d %H:%M:%S")
        timestamp1 = time.mktime(dateTime1.timetuple())
        timestamp2 = time.mktime(dateTime2.timetuple())
        self.t_begin = timestamp1
        self.t_end = timestamp2

        # 更新按钮
        self.btn = QtWidgets.QPushButton('点击查询')
        self.btn.clicked.connect(self.onButtonClick)
        self.btn.setStyleSheet("QPushButton {"
                               "background-color: rgb(0,175,219);"  # 设置背景颜色
                               "color: white;"  # 设置文本颜色
                               "border-radius: 5px;"  # 设置边框圆角
                               "padding: 10px 20px;"  # 设置内边距
                               "border-width: 5px;"
                               "border-color: rgb(108, 166, 205);"
                               "border-style: outset;"
                               "}"
                               "QPushButton:hover {background-color: rgb(108, 166, 205);}"
                               "QPushButton:pressed {background-color: rgb(74, 112, 139);}")

        # 导出按钮
        self.btnxls = QtWidgets.QPushButton('导出')
        self.btnxls.clicked.connect(self.onButtonClick_export_xls)
        self.btnxls.setStyleSheet("QPushButton {"
                                  "background-color: rgb(0,175,219);"  # 设置背景颜色
                                  "color: white;"  # 设置文本颜色
                                  "border-radius: 5px;"  # 设置边框圆角
                                  "padding: 10px 20px;"  # 设置内边距
                                  "border-width: 5px;"
                                  "border-color: rgb(108, 166, 205);"
                                  "border-style: outset;"
                                  "}"
                                  "QPushButton:hover {background-color: rgb(108, 166, 205);}"
                                  "QPushButton:pressed {background-color: rgb(74, 112, 139);}")

        self.splitter_paget.addWidget(self.label1)
        self.splitter_paget.addWidget(self.dateEdit1)
        self.splitter_paget.addWidget(self.label2)
        self.splitter_paget.addWidget(self.dateEdit2)
        self.splitter_paget.addWidget(self.btn)
        self.splitter_paget.addWidget(self.btnxls)
        # ###################

        self.toolbar = QToolBar(self)
        self.toolbar.setMovable(False)
        self.toolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.TABLE = QtWidgets.QTableWidget(self)
        self.TABLE.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.TABLE.horizontalHeader().setStretchLastSection(True)
        self.TABLE.horizontalHeader().setStyleSheet("QHeaderView::section{background:rgb(176,226,255)};")
        self.TABLE.verticalHeader().setStyleSheet("QHeaderView::section{background:rgb(176,226,255)};")

        self.grid_main.addWidget(self.splitter_paget, 0, 0)
        self.grid_main.addWidget(self.TABLE, 1, 0, 1, 2)

        self.grid_main.setColumnStretch(1, 1)

        self.setCentralWidget(self.central)

    def initData(self):
        self.conn = sqlite3.connect(str(self.db_path))
        self.cursor = self.conn.cursor()
        # self.P_CURRENT.setValue(1)
        self.page_content()

    def page_content(self, i=1):
        """ 根据页数显示页面内容 """
        # self.update_total_pages()

        self.sql2 = self.sql + ' where 时间 between %s and %s' % (self.t_begin, self.t_end)
        self.result = self.cursor.execute(self.sql2).fetchall()
        # up, down = (i - 1) * self.table_limit, i * self.table_limit
        self.update_table(self.result)

    # def update_total_pages(self):
    #     """ 更新总页数 """
    #     # sql = 'select count(索引) from %s' % self.table_name
    #     sql = self.sql.replace('*', 'count(索引)')
    #     total = self.cursor.execute(sql).fetchone()[0]
    #     if total == 0 or total % self.table_limit:
    #         total_pages = int(total / self.table_limit) + 1
    #     else:
    #         total_pages = int(total / self.table_limit)
    #     self.P_TOTAL.setText(str(total_pages))
    #     self.P_CURRENT.setMaximum(total_pages)

    def onButtonClick(self):
        self.TABLE.clearContents()
        Time1 = str(self.dateEdit1.dateTime().toPyDateTime())
        Time2 = str(self.dateEdit2.dateTime().toPyDateTime())
        dateTime1 = datetime.datetime.strptime(Time1, "%Y-%m-%d %H:%M:%S")
        dateTime2 = datetime.datetime.strptime(Time2, "%Y-%m-%d %H:%M:%S")
        timestamp1 = time.mktime(dateTime1.timetuple())
        timestamp2 = time.mktime(dateTime2.timetuple())
        self.t_begin = timestamp1
        self.t_end = timestamp2
        self.page_content()

    def onButtonClick_export_xls(self):
        Time1 = str(self.dateEdit1.dateTime().toPyDateTime())
        Time2 = str(self.dateEdit2.dateTime().toPyDateTime())
        dateTime1 = datetime.datetime.strptime(Time1, "%Y-%m-%d %H:%M:%S")
        dateTime2 = datetime.datetime.strptime(Time2, "%Y-%m-%d %H:%M:%S")
        timestamp1 = time.mktime(dateTime1.timetuple())
        timestamp2 = time.mktime(dateTime2.timetuple())
        self.t_begin = timestamp1
        self.t_end = timestamp2
        self.update_threshold()
        workbook = xlwt.Workbook(encoding='utf-8')  # 新建工作簿
        sheet1 = workbook.add_sheet("sheet1")  # 新建sheet
        for idx, i in enumerate(self.table_left_class):
            sheet1.write(idx + 1, 0, i)
        for idx, j in enumerate(self.table_header):
            sheet1.write(0, idx + 1, j)
        for i, data in enumerate(self.data_list):
            sheet1.write(1, i + 1, str(self.count_list[i]))
            sheet1.write(2, i + 1, str(self.Max_list[i]))
            sheet1.write(3, i + 1, str(self.Min_list[i]))
            sheet1.write(4, i + 1, str(self.Ave_list[i]))
            # sheet1.write(5, i+1, str(self.SigmaL_list[i]))
            # sheet1.write(6, i+1, str(self.Sigma_list[i]))
            # sheet1.write(7, i+1, str(self.Sigma6_list[i]))
            # sheet1.write(8, i+1, str(self.Sigma4_list[i]))
            # sheet1.write(9, i+1, str(self.Sigma3_list[i]))
            # sheet1.write(10, i+1, str(self.Sigma3a_list[i]))
            # sheet1.write(11, i+1, str(self.Sigma4a_list[i]))
            # sheet1.write(12, i+1, str(self.Sigma6a_list[i]))
            # sheet1.write(13, i+1, str(self.Sigma6a_list[i]))
            # sheet1.write(14, i+1, str(self.Sigma6_list[i]))
            # sheet1.write(15, i+1, str(self.AMax_list[i]))
            # sheet1.write(16, i+1, str(self.AMin_list[i]))
            # sheet1.write(17, i+1, str(self.CP_list[i]))
            # sheet1.write(18, i+1, str(self.CPK_list[i]))
            # sheet1.write(19, i+1, str(self.UL_list[i]))
            # sheet1.write(20, i+1, str(self.Sigma4_list[i]))
            # sheet1.write(21, i+1, str(self.threshold[i]))

        exl_name = 'ZS-' + str(datetime.datetime.fromtimestamp(self.t_begin).strftime("%Y-%m-%d-%H-%M-%S")) + '-' + \
                   str(datetime.datetime.fromtimestamp(self.t_end).strftime("%Y-%m-%d-%H-%M-%S")) + '.xlsx'
        exl_dir = str(Settings.BASE_DIR / 'result/')
        workbook.save(exl_dir + '\\' + exl_name)  # 保存
        reply = QtWidgets.QMessageBox.information(self, '提示', exl_name + '保存至result成功！是否查看',
                                                  QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
        if reply == QtWidgets.QMessageBox.Yes:
            QDesktopServices.openUrl(QUrl('file:///' + exl_dir))

    @logger.catch(reraise=True)
    def update_table(self, data):
        """ 更新数据表 """
        self.reset()
        self.TABLE.setRowCount(len(self.table_left_class))
        for row_data in data:
            defect_name = row_data[3].split('|')
            data_size = row_data[4].split('|')
            print(row_data)
            for i, name in enumerate(defect_name):
                if len(name) < 2:
                    continue
                index = self.table_header.index(name)

                self.data_list[index].append(name)
                self.data_size_list[index].append(data_size[i])
                wh = data_size[i]
                w = float(wh.split('x')[0])
                h = float(wh.split('x')[1])
                self.data_area_list[index].append(w * h)

        # # 计算各种数据
        for i, data1 in enumerate(self.data_list):
            self.count_list[i] = len(data1)
            # print(self.data_area_list[i])
            max_data = max(self.data_area_list[i]) if len(self.data_area_list[i]) > 0 else 0
            min_data = min(self.data_area_list[i]) if len(self.data_area_list[i]) > 0 else 0
            avg = np.mean(self.data_area_list[i]) if len(self.data_area_list[i]) > 0 else 0
            self.Max_list[i] = '%.4g' % max_data
            self.Min_list[i] = '%.4g' % min_data
            self.Ave_list[i] = '%.4g' % avg

        for i, data in enumerate(self.data_list):
            self.TABLE.setItem(0, i, QtWidgets.QTableWidgetItem(str(self.count_list[i])))
            self.TABLE.setItem(1, i, QtWidgets.QTableWidgetItem(str(self.Max_list[i])))
            self.TABLE.setItem(2, i, QtWidgets.QTableWidgetItem(str(self.Min_list[i])))
            self.TABLE.setItem(3, i, QtWidgets.QTableWidgetItem(str(self.Ave_list[i])))

    def ui_table_h_header(self, v: list):
        font = QFont()
        font.setPointSize(12)  # 设置字体大小为12
        self.TABLE.horizontalHeader().setFont(font)
        self.TABLE.setColumnCount(len(v))
        self.TABLE.setHorizontalHeaderLabels(v)
        self.TABLE.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.TABLE.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)

    def ui_table_l_left(self, v: list):
        font = QFont()
        font.setPointSize(12)  # 设置字体大小为12
        self.TABLE.verticalHeader().setFont(font)
        self.TABLE.setRowCount(len(v))
        self.TABLE.setVerticalHeaderLabels(v)

    def _cmk(self, mean, std, usl=None, ucl=None):
        if not usl:
            usl = random.uniform(1.67, 2.33) * (3 * std) + mean
        cmk = (usl - mean) / (3 * std)
        # cmk = min((usl - mean), (mean - ucl)) / (3 * std)
        return cmk

    def _sigma(self, data, mean, std, n):
        inlier = []
        threshold_l = mean - n * std
        threshold_r = mean + n * std
        for sub in data:
            if threshold_l < sub < threshold_r:
                inlier.append(sub)
        res = len(inlier) / len(data)
        return res
